package cuong.ptit.androidvn;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.BaseAdapter;
import android.widget.ListAdapter;
import android.widget.SimpleAdapter;
import cuong.ptit.andoridvn.R;
import cuong.ptit.androidvn.helper.Function;
import cuong.ptit.androidvn.helper.JSONParser;
import cuong.ptit.androidvn.widget.PullAndLoadListView;
import cuong.ptit.androidvn.widget.PullAndLoadListView.OnLoadMoreListener;
import cuong.ptit.androidvn.widget.PullToRefreshListView.OnRefreshListener;

/*
 * @author LeCuong 
 * @version 1.0
 */

public class GetThreadStart extends ListActivity {

	private ProgressDialog pDialog;
	private int LoadThreadMore = 10, in = 0;
	private String user_name, user_hash, user_id;
	// JSON
	JSONParser jsonParser = new JSONParser();
	ArrayList<HashMap<String, String>> listThread;
	ArrayList<HashMap<String, String>> listThreadLoad;
	ArrayList<HashMap<String, String>> listForum;
	private static final String url_forum = "http://android.vn/api.php?action=getNodes&hash=d8e8fca2dc0f896fd7cb4cb0031ba249&node_type=forum";
	private static final String TAG_ID_N = "node_id";
	private static final String TAG_TITLE_N = "title";

	private static final String url = "http://android.vn/api.php?action=getthreads&hash=d8e8fca2dc0f896fd7cb4cb0031ba249";
	private static final String TAG_ID_THRED = "thread_id";
	private static final String TAG_ID_NODE = "node_id";
	private static final String TAG_TITLE = "title";
	private static final String TAG_USER = "username";
	private static final String TAG_VIEW = "view_count";
	private static final String TAG_REPLY = "reply_count";
	private static final String TAG_DATE = "post_date";
	private static final String TAG_BOX = "nameBox";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.get_thread_user_activity);

		// get intent
		Intent i = getIntent();
		user_id = i.getStringExtra("user_idname");
		user_name = i.getStringExtra("user_name");
		user_hash = i.getStringExtra("user_hash");

		listThread = new ArrayList<HashMap<String, String>>();
		new LoadThredUser().execute();

		// refresh list view
		((PullAndLoadListView) getListView())
				.setOnRefreshListener(new OnRefreshListener() {

					@Override
					public void onRefresh() {

						new PullRefreshList().execute();
					}
				});

		((PullAndLoadListView) getListView())
				.setOnLoadMoreListener(new OnLoadMoreListener() {

					@Override
					public void onLoadMore() {

						LoadThreadMore = LoadThreadMore + 10;
						in = listThread.size();

						new LoadMoreList().execute();

					}
				});

	}

	// load more listview

	class LoadMoreList extends AsyncTask<String, String, String> {

		@Override
		protected String doInBackground(String... agrs) {

			if (isCancelled()) {
				return null;
			}

			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
			}

			int aa = 10;
			String limit = String.valueOf(LoadThreadMore);
			// check json loadmore 1
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			params.add(new BasicNameValuePair("author", user_id));
			params.add(new BasicNameValuePair("limit", limit));
			listThreadLoad = new ArrayList<HashMap<String, String>>();

			String jsonLoad = jsonParser.makeHttpRequest(url, "GET", params);

			try {

				JSONObject threads = new JSONObject(jsonLoad);
				JSONObject thread = threads.getJSONObject("threads");

				Iterator<?> keys = thread.keys();

				while (keys.hasNext()) {
					String key = (String) keys.next();
					JSONObject c = thread.getJSONObject(key);

					String idThread = c.getString(TAG_ID_THRED);
					String idNode = c.getString(TAG_ID_NODE);
					String title = c.getString(TAG_TITLE);
					String date = c.getString(TAG_DATE);
					String view = c.getString(TAG_VIEW);
					String reply = c.getString(TAG_REPLY);
					String user = c.getString(TAG_USER);
					String box = Function.GetNameBox(listForum, idNode);

					HashMap<String, String> map = new HashMap<String, String>();
					map.put(TAG_ID_THRED, idThread);
					map.put(TAG_ID_NODE, idNode);
					map.put(TAG_TITLE, title);
					map.put(TAG_DATE, date);
					map.put(TAG_VIEW, view);
					map.put(TAG_REPLY, reply);
					map.put(TAG_USER, user);
					map.put(TAG_BOX, box);

					listThreadLoad.add(map);

				}

			} catch (JSONException e) {
				e.printStackTrace();
			}

			// sort list
			Function.CollectionSortBA(listThreadLoad, "post_date");

			if (listThread.size() < listThreadLoad.size()) {
				for (int ab = in; ab < listThreadLoad.size(); ab++) {
					HashMap<String, String> a = listThreadLoad.get(ab);
					listThread.add(a);
				}
			}

			Function.CollectionSort(listThread, "post_date");
			Log.d("array", "list:" + listThread.size() + "load:"
					+ listThreadLoad.size() + "in:" + in);

			// -------------------------------------------------------------------------

			Function.CollectionSortBA(listThread, "post_date");
			return null;
		}

		@Override
		protected void onPostExecute(String result) {
			((BaseAdapter) getListAdapter()).notifyDataSetChanged();
			((PullAndLoadListView) getListView()).onLoadMoreComplete();
			super.onPostExecute(result);
		}

		@Override
		protected void onCancelled() {
			((PullAndLoadListView) getListView()).onLoadMoreComplete();
			super.onCancelled();
		}
	}

	// refresh list view
	class PullRefreshList extends AsyncTask<String, String, String> {

		@Override
		protected String doInBackground(String... params) {
			if (isCancelled()) {
				return null;
			}

			try {
				Thread.sleep(3000);
			} catch (InterruptedException e) {
			}

			// clear list thread
			listThread.clear();

			// add new list thread

			List<NameValuePair> params1 = new ArrayList<NameValuePair>();
			params1.add(new BasicNameValuePair("author", user_id));
			String json = jsonParser.makeHttpRequest(url, "GET", params1);

			// check json limit 10
			List<NameValuePair> params2 = new ArrayList<NameValuePair>();
			params2.add(new BasicNameValuePair("author", user_id));
			params2.add(new BasicNameValuePair("limit", "10"));
			String jsonNew = jsonParser.makeHttpRequest(url, "GET", params2);

			try {

				JSONObject threads = new JSONObject(json);
				JSONObject thread = threads.getJSONObject("threads");

				Iterator<?> keys = thread.keys();

				while (keys.hasNext()) {
					String key = (String) keys.next();
					JSONObject c = thread.getJSONObject(key);
					String idThread = c.getString(TAG_ID_THRED);
					String idNode = c.getString(TAG_ID_NODE);
					String title = c.getString(TAG_TITLE);
					String date = c.getString(TAG_DATE);
					String view = c.getString(TAG_VIEW);
					String reply = c.getString(TAG_REPLY);
					String user = c.getString(TAG_USER);
					String box = Function.GetNameBox(listForum, idNode);

					HashMap<String, String> map = new HashMap<String, String>();
					map.put(TAG_ID_THRED, idThread);
					map.put(TAG_ID_NODE, idNode);
					map.put(TAG_TITLE, title);
					map.put(TAG_DATE, date);
					map.put(TAG_VIEW, view);
					map.put(TAG_REPLY, reply);
					map.put(TAG_USER, user);
					map.put(TAG_BOX, box);
					listThread.add(map);

				}

			} catch (JSONException e) {
				e.printStackTrace();
			}
			Function.CollectionSortBA(listThread, "post_date");

			LoadThreadMore = 10;
			in = 10;
			return null;
		}

		@Override
		protected void onPostExecute(String result) {
			((BaseAdapter) getListAdapter()).notifyDataSetChanged();
			((PullAndLoadListView) getListView()).onRefreshComplete();
			super.onPostExecute(result);
		}

		@Override
		protected void onCancelled() {
			((PullAndLoadListView) getListView()).onRefreshComplete();
			super.onCancelled();
		}

	}

	// set list adapter
	class LoadThredUser extends AsyncTask<String, String, String> {
		// load Progress
		@Override
		protected void onPreExecute() {
			pDialog = new ProgressDialog(GetThreadStart.this);
			pDialog.setMessage("Loading ....");
			pDialog.setIndeterminate(false);
			pDialog.setCancelable(false);
			pDialog.show();
			super.onPreExecute();
		}

		// load json
		@Override
		protected String doInBackground(String... args) {

			listForum = new ArrayList<HashMap<String, String>>();
			List<NameValuePair> pa = new ArrayList<NameValuePair>();
			String jsonForum = jsonParser.makeHttpRequest(url_forum, "GET", pa);

			listThreadLoad = new ArrayList<HashMap<String, String>>();
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			params.add(new BasicNameValuePair("author", user_id));

			String json = jsonParser.makeHttpRequest(url, "GET", params);

			/*// check json new
			List<NameValuePair> params2 = new ArrayList<NameValuePair>();
			params2.add(new BasicNameValuePair("author", user_id));
			params2.add(new BasicNameValuePair("limit", "20"));
			String jsonNew = jsonParser.makeHttpRequest(url, "GET", params2);

			Log.d("json length", "jsonnew = " + jsonNew.length() + "json = "
					+ json.length());*/

			try {

				// json load forum

				JSONObject forums = new JSONObject(jsonForum);
				JSONObject forum = forums.getJSONObject("nodes");

				Iterator<?> keysf = forum.keys();

				while (keysf.hasNext()) {
					String key = (String) keysf.next();
					JSONObject c = forum.getJSONObject(key);

					String id_node = c.getString(TAG_ID_N);
					String title_node = c.getString(TAG_TITLE_N);

					HashMap<String, String> map = new HashMap<String, String>();
					map.put(TAG_ID_N, id_node);
					map.put(TAG_TITLE_N, title_node);

					listForum.add(map);
				}

				// json load thread
				JSONObject threads = new JSONObject(json);
				JSONObject thread = threads.getJSONObject("threads");

				Iterator<?> keys = thread.keys();

				while (keys.hasNext()) {
					String key = (String) keys.next();
					JSONObject c = thread.getJSONObject(key);

					String idThread = c.getString(TAG_ID_THRED);
					String idNode = c.getString(TAG_ID_NODE);
					String title = c.getString(TAG_TITLE);
					String date = c.getString(TAG_DATE);
					String view = c.getString(TAG_VIEW);
					String reply = c.getString(TAG_REPLY);
					String user = c.getString(TAG_USER);
					String box = Function.GetNameBox(listForum, idNode);

					HashMap<String, String> map = new HashMap<String, String>();
					map.put(TAG_ID_THRED, idThread);
					map.put(TAG_ID_NODE, idNode);
					map.put(TAG_TITLE, title);
					map.put(TAG_DATE, date);
					map.put(TAG_VIEW, view);
					map.put(TAG_REPLY, reply);
					map.put(TAG_USER, user);
					map.put(TAG_BOX, box);

					listThread.add(map);

				}

			} catch (JSONException e) {
				e.printStackTrace();
			}

			Log.d("thread", ">" + listThread);

			// sort list to date post--
			Function.CollectionSortBA(listThread, "post_date");
			return null;
		}

		// set adapter lisview

		@Override
		protected void onPostExecute(String result) {
			pDialog.dismiss();
			runOnUiThread(new Runnable() {
				public void run() {

					ListAdapter adapter = new SimpleAdapter(getBaseContext(),
							listThread, R.layout.list_item_getthread_start,
							new String[] { TAG_USER, TAG_VIEW, TAG_REPLY,
									TAG_DATE, TAG_TITLE, TAG_BOX }, new int[] {
									R.id.tv_user_getThreadStart,
									R.id.tv_view_getThreadStart,
									R.id.tv_post_getThreadStart,
									R.id.tv_date_getThreadStart,
									R.id.tv_title_getThreadStart,
									R.id.tv_box_getThreadStart });

					setListAdapter(adapter);

				}
			});
			super.onPostExecute(result);
		}
	}

}
